/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import dao.exceptions.NonexistentEntityException;
import dao.exceptions.RollbackFailureException;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import javax.transaction.UserTransaction;
import pojos.Expenses;
import pojos.Projects;
import pojos.Employees;
import pojos.Currencies;

/**
 *
 * @author A7med Kotb
 */
public class ExpensesJpaController implements Serializable {

    public ExpensesJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Expenses expenses) throws RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Projects project = expenses.getProject();
            if (project != null) {
                project = em.getReference(project.getClass(), project.getProId());
                expenses.setProject(project);
            }
            Employees employee = expenses.getEmployee();
            if (employee != null) {
                employee = em.getReference(employee.getClass(), employee.getEmpId());
                expenses.setEmployee(employee);
            }
            Currencies currency = expenses.getCurrency();
            if (currency != null) {
                currency = em.getReference(currency.getClass(), currency.getCurrId());
                expenses.setCurrency(currency);
            }
            Employees createdBy = expenses.getCreatedBy();
            if (createdBy != null) {
                createdBy = em.getReference(createdBy.getClass(), createdBy.getEmpId());
                expenses.setCreatedBy(createdBy);
            }
            em.persist(expenses);
            if (project != null) {
                project.getExpensesCollection().add(expenses);
                project = em.merge(project);
            }
            if (employee != null) {
                employee.getExpensesCollection().add(expenses);
                employee = em.merge(employee);
            }
            if (currency != null) {
                currency.getExpensesCollection().add(expenses);
                currency = em.merge(currency);
            }
            if (createdBy != null) {
                createdBy.getExpensesCollection().add(expenses);
                createdBy = em.merge(createdBy);
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Expenses expenses) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Expenses persistentExpenses = em.find(Expenses.class, expenses.getExpId());
            Projects projectOld = persistentExpenses.getProject();
            Projects projectNew = expenses.getProject();
            Employees employeeOld = persistentExpenses.getEmployee();
            Employees employeeNew = expenses.getEmployee();
            Currencies currencyOld = persistentExpenses.getCurrency();
            Currencies currencyNew = expenses.getCurrency();
            Employees createdByOld = persistentExpenses.getCreatedBy();
            Employees createdByNew = expenses.getCreatedBy();
            if (projectNew != null) {
                projectNew = em.getReference(projectNew.getClass(), projectNew.getProId());
                expenses.setProject(projectNew);
            }
            if (employeeNew != null) {
                employeeNew = em.getReference(employeeNew.getClass(), employeeNew.getEmpId());
                expenses.setEmployee(employeeNew);
            }
            if (currencyNew != null) {
                currencyNew = em.getReference(currencyNew.getClass(), currencyNew.getCurrId());
                expenses.setCurrency(currencyNew);
            }
            if (createdByNew != null) {
                createdByNew = em.getReference(createdByNew.getClass(), createdByNew.getEmpId());
                expenses.setCreatedBy(createdByNew);
            }
            expenses = em.merge(expenses);
            if (projectOld != null && !projectOld.equals(projectNew)) {
                projectOld.getExpensesCollection().remove(expenses);
                projectOld = em.merge(projectOld);
            }
            if (projectNew != null && !projectNew.equals(projectOld)) {
                projectNew.getExpensesCollection().add(expenses);
                projectNew = em.merge(projectNew);
            }
            if (employeeOld != null && !employeeOld.equals(employeeNew)) {
                employeeOld.getExpensesCollection().remove(expenses);
                employeeOld = em.merge(employeeOld);
            }
            if (employeeNew != null && !employeeNew.equals(employeeOld)) {
                employeeNew.getExpensesCollection().add(expenses);
                employeeNew = em.merge(employeeNew);
            }
            if (currencyOld != null && !currencyOld.equals(currencyNew)) {
                currencyOld.getExpensesCollection().remove(expenses);
                currencyOld = em.merge(currencyOld);
            }
            if (currencyNew != null && !currencyNew.equals(currencyOld)) {
                currencyNew.getExpensesCollection().add(expenses);
                currencyNew = em.merge(currencyNew);
            }
            if (createdByOld != null && !createdByOld.equals(createdByNew)) {
                createdByOld.getExpensesCollection().remove(expenses);
                createdByOld = em.merge(createdByOld);
            }
            if (createdByNew != null && !createdByNew.equals(createdByOld)) {
                createdByNew.getExpensesCollection().add(expenses);
                createdByNew = em.merge(createdByNew);
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = expenses.getExpId();
                if (findExpenses(id) == null) {
                    throw new NonexistentEntityException("The expenses with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Expenses expenses;
            try {
                expenses = em.getReference(Expenses.class, id);
                expenses.getExpId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The expenses with id " + id + " no longer exists.", enfe);
            }
            Projects project = expenses.getProject();
            if (project != null) {
                project.getExpensesCollection().remove(expenses);
                project = em.merge(project);
            }
            Employees employee = expenses.getEmployee();
            if (employee != null) {
                employee.getExpensesCollection().remove(expenses);
                employee = em.merge(employee);
            }
            Currencies currency = expenses.getCurrency();
            if (currency != null) {
                currency.getExpensesCollection().remove(expenses);
                currency = em.merge(currency);
            }
            Employees createdBy = expenses.getCreatedBy();
            if (createdBy != null) {
                createdBy.getExpensesCollection().remove(expenses);
                createdBy = em.merge(createdBy);
            }
            em.remove(expenses);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Expenses> findExpensesEntities() {
        return findExpensesEntities(true, -1, -1);
    }

    public List<Expenses> findExpensesEntities(int maxResults, int firstResult) {
        return findExpensesEntities(false, maxResults, firstResult);
    }

    private List<Expenses> findExpensesEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Expenses.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Expenses findExpenses(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Expenses.class, id);
        } finally {
            em.close();
        }
    }

    public int getExpensesCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Expenses> rt = cq.from(Expenses.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
